<template>
  <!-- nav-bar -->
  <div class="Login-nav">
    <van-nav-bar title="登录" left-text="" left-arrow @click-left="onClickLeft" />
  </div>

  <!-- ref验证规则 submitForm表单提交事件-->
  <van-form @submit="submitForm" @failed="onFailed" ref="ruleUserRef" :model="form">

    <van-cell-group>
      <!-- clearable：启用清除控件 rules校验规则 -->
      <van-field v-model="form.username" label="账号：" placeholder="请输入账号" clearable name="username"
        :rules="usernameRules">
      </van-field>
    </van-cell-group>

    <van-cell-group>
      <van-field v-model="form.password" label="密码：" placeholder="请输入密码" clearable name="password" type="password"
        :rules="passwordRules">
      </van-field>

    </van-cell-group>
    <!-- 设置一个块级圆形，type为主要类型的按钮 -->
    <van-cell-group>
      <van-button block round type="primary" native-type="submit">登录</van-button>
    </van-cell-group>
  </van-form>
</template>

<script setup>
import { ref, reactive } from 'vue'
import useToken from '../stores/token';
import useUser from '../stores/user';
import { login } from '../api/index';
import { getUser } from '../api/index';
// 登录成功跳转到我的页面
import { useRouter } from 'vue-router';

const router = useRouter()

const { updateToken } = useToken()
const { updateUser } = useUser()

// 响应式对象
const form = reactive({
  username: 'demo1',
  password: '123456'
})

//navBar返回上级
const onClickLeft = () => history.back()

const ruleUserRef = ref()
// 定义验证规则，是否为必选字段
const usernameRules = ref([
  { required: true, message: '用户名不能为空' },
])
const passwordRules = ref([
  { required: true, message: '密码不能为空' },
])

// 表单提交函数
const submitForm = async values => {
  //异步
  const data = await login(values)
  if (data) {
    updateToken(data.token)
    const user = await getUser()
    updateUser({
      isLogin: true,
      username: user.username,
      avatar: user.avatar
    })
    // 登录跳转
    router.push({ name: 'user' })
  }
}
const onFailed = errorInfo => {
}


</script>

<style scoped>
.Login-nav {
  --van-nav-bar-background: #ff8001;
  --van-nav-bar-title-text-color: #fff;
  --van-nav-bar-icon-color: #fff;
}
</style>